import serial
import matplotlib.pyplot as plt
import matplotlib.animation as animation

ser = serial.Serial('COM16', 115200, timeout=1)

plt.ion()
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'r-', animated=True)

def init():
    ax.set_xlim(0, 100)
    ax.set_ylim(0, 100)
    return ln,


def update(frame):
    data = ser.readline()

    data_str = str(data, 'utf-8')
    data_items = data_str.split(',')
    extracted_values = {} 
    for item in data_items:
        key_value = item.split('=')  # 分割每个键值对
        if len(key_value) == 2:  # 确保每个元素都是键值对
            key, value = key_value
            extracted_values[key.strip()] = int(value.strip())  # 转换值为整数并存储
    try:
        if data:
            y = int(extracted_values['x'])
            xdata.append(frame)
            ydata.append(y)
            xdata = xdata[-100:]
            ydata = ydata[-100:]
            ln.set_data(xdata, ydata)
        return ln,
    except:
        None

# while True:
#     if ser.in_waiting > 0:
#         data = ser.readline()
        
#         data_str = str(data, 'utf-8')

#         data_items = data_str.split(',')
#         extracted_values = {} 
#         for item in data_items:
#             key_value = item.split('=')  # 分割每个键值对
#             if len(key_value) == 2:  # 确保每个元素都是键值对
#                 key, value = key_value
#                 extracted_values[key.strip()] = int(value.strip())  # 转换值为整数并存储
#         # print(extracted_values)  # 打印提取出的键值对
#         try:
#             print(extracted_values['x'])
#         except:
#             None

while True:
    ani = animation.FuncAnimation(fig, update, frames=range(1000), init_func=init, blit=True)
    plt.show()